package io.pumelo.bug;

import io.pumelo.Pumelo;
import io.pumelo.bean.BugCache;
import io.pumelo.tools.Encrypt;

import java.text.MessageFormat;
import java.util.*;

/**
 * Created by Studio on 2017/6/28.
 */
public class Bug {
    private Pumelo context;
    private Hashtable<String,BugCache> hashtable = new Hashtable<String, BugCache>();
    private final String url = "http://bug.yueare.com/v1/bug/collection";

    public Bug( Pumelo context) {
        this.context = context;
    }

    public void Report(Exception exception)
    {
        String error = "File:{0} / Class:{1} / Method:{2} / Line:{3} / Error:{4}";
        if(exception.getStackTrace().length > 0){
            error = MessageFormat.format(error,
                    exception.getStackTrace()[0].getFileName(),
                    exception.getStackTrace()[0].getClassName(),
                    exception.getStackTrace()[0].getMethodName(),
                    exception.getStackTrace()[0].getLineNumber(),
                    exception.toString()
            );
        }else{
            error = exception.toString();
        }

        String exceprionStr = exception.toString();

        if(exceprionStr.length()>100){
            exceprionStr = exceprionStr.substring(0,99);
        }
        Report(exceprionStr,error);
    }

    public void Report(String title, String content)
    {
        String errorMd5 = Encrypt.MD5(content);

        if( errorMd5 == null){
            return;
        }
        if(!hashtable.containsKey(errorMd5)){
            hashtable.put(errorMd5,new BugCache(errorMd5));
        }else{
            BugCache bugCache = hashtable.get(errorMd5);
            long timestamp = System.currentTimeMillis();

            if(timestamp - bugCache.getTimestamp() > 1000){
                bugCache.setTimestamp(timestamp);
            }else{
                return;
            }
        }



        System.out.println(title);
        System.out.println(content);



        long timestamp = System.currentTimeMillis();

        HashMap<String,Object> hashMap = new HashMap<String,Object>();

        hashMap.put("appkey",context.getAppkey());
        hashMap.put("title",title);
        hashMap.put("content",content);
        hashMap.put("timestamp",timestamp);

        Collection<String> keyset= hashMap.keySet();

        List<String> list = new ArrayList<String>(keyset);
        Collections.sort(list);
        //拼接参数
        String signStr = "";
        for (String aList : list) {
            signStr += "/" + aList + "/" + hashMap.get(aList);
        }

        String signature = Encrypt.hmac_sha1(signStr,context.getSkey());

        String param = "appkey="+context.getAppkey()+"&title="+title+"&content="+content +
                "&timestamp="+timestamp+"&sign="+signature;



        new BugThread(url,param).start();
    }

}
